#!/usr/bin/env bash
# Coordinator initialization script
CUR_PATH="$(dirname "${BASH_SOURCE[0]}")"
# shellcheck source=./common.sh
source "${CUR_PATH}/common.sh"

# initialize dependencies.
# shellcheck source=./initialize_env_dependencies
source "${CUR_PATH}/initialize_env_dependencies" || exit $?

log:info "Initializing coordinator node @ ${PG_NODE}"

if [ "${POD_INDEX}" -eq 0 ]; then
  log:info "Starting postgres as master coordinator"
  # initialize the database.
  # shellcheck source=./initialize_postgres_db
  source "${CUR_PATH}/initialize_postgres_db" || exit $?
  # start the node register in the bg.
  "${CUR_PATH}/register_node" &
else
  log:info "Starting postgres as standby coordinator"
  # initialize the database.
  # shellcheck source=./initialize_standby_coordinator
  source "${CUR_PATH}/initialize_standby_coordinator" || exit $?
fi

# starting postgres.
postgres \
  -D "${PGDATA}" \
  -h "${PG_HOST}" \
  -p "${PG_PORT}" \
  --coordinator